package com.zx.cloud.controller;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zx.cloud.ApiVersion;
import com.zx.cloud.RequestLogging;
import com.zx.cloud.Shift;
import com.zx.cloud.common.filter.CurrentUserId;
import com.zx.cloud.common.filter.IgnoreAuth;
import com.zx.cloud.domain.ClientInfo;
import com.zx.cloud.domain.ClientLoanOrder;
import com.zx.cloud.domain.Dict;
import com.zx.cloud.domain.LoanOrder;
import com.zx.cloud.domain.RepayOrder;
import com.zx.cloud.domain.User;
import com.zx.cloud.model.response.ObjectDataResponse;
import com.zx.cloud.service.ClientRiskService;
import com.zx.cloud.service.DictService;
import com.zx.cloud.service.LoanOrderService;
import com.zx.cloud.service.LogService;
import com.zx.cloud.service.RepayOrderService;
import com.zx.cloud.service.UserService;
import com.zx.cloud.util.Page;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 * @ClassName: LoanOrderController
 * @Description: 借款管理
 * @author: Administrator
 * @date: 2017年10月30日 下午4:18:37
 */
@RestController
@RequestMapping(value = ApiVersion.PROVIDER_V1_PREFIX+"/loan")
public class LoanOrderController{
	private static final Logger logger=Logger.getLogger(LoanOrderController.class);
	static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	@Autowired
	private LoanOrderService loanOrderService;
	@Autowired
	private RepayOrderService repayOrderService;
	@Autowired
	private DictService dictService;
	@Autowired
	private LogService  logService; 
	@Autowired
	private ClientRiskService  clientRiskService; 
	@Autowired
	private UserService   userService;
	
	@RequestLogging
	@ApiOperation(value = "借款管理-借款订单列表", notes = "借款管理-借款订单列表")
	@RequestMapping(value = "/getLoanOrderList", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<LoanOrder>> getLoanOrderList(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		User  user=userService.get(userId);
		loanOrder.setVerifyCode(user.getVerifyCode());
		
		Page<LoanOrder> loanOrderList=loanOrderService.page(loanOrder);
		logService.addLog(userId, "借款管理-借款订单列表", 0);
		return new ObjectDataResponse<Page<LoanOrder>>(loanOrderList);
	}
	
	@IgnoreAuth
	@RequestLogging
	@ApiOperation(value = "获取利率", notes = "获取利率")
	@RequestMapping(value = "/getDitRate", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<List<Dict>> getDitRate(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId){
		 Dict dict=new Dict();
		 dict.setParentCode("R0001");
		 List<Dict> dicts=dictService.getDitRate(dict);
		 
		return new ObjectDataResponse<List<Dict>>(dicts);
	}
	@IgnoreAuth
	@RequestLogging
	@ApiOperation(value = "ios审核", notes = "ios审核")
	@RequestMapping(value = "/getIosCheck", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<List<Dict>> getIosCheck(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId){
		 Dict dict=new Dict();
		 dict.setParentCode("IC0001");
		 List<Dict> dicts=dictService.getDitRate(dict);
		return new ObjectDataResponse<List<Dict>>(dicts);
	}
	@RequestLogging
	@ApiOperation(value = "借款管理-创建借款订单", notes = "借款管理-创建借款订单")
	@RequestMapping(value = "/createLoanOrder", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> createLoanOrder(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody  LoanOrder loanOrder) throws NoSuchAlgorithmException, InvalidKeySpecException{
		Long clientId=loanOrder.getClientId();
		if(clientId == null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[clientId]会员主键为空啦！");	
		}
		BigDecimal loanAmount=loanOrder.getLoanAmount();
		if(loanAmount.compareTo(new BigDecimal(0)) == 0){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[loanAmount]借款金额为空啦！");	
		}else if(loanAmount.compareTo(new BigDecimal(100)) == -1 ||  loanAmount.compareTo(new BigDecimal(1500)) == 1){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[loanAmount]借款金额，最低100，最大不超过1500！");	
		}else if(loanAmount.intValue() % 100 !=0){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[loanAmount]借款金额，必须是100的整数倍数");	
		}
		Integer loanTerm=loanOrder.getLoanTerm();
		if(loanTerm == null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[loanTerm]借款期限为空啦！");	
		}
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("clientId", clientId);
		List<LoanOrder>  loanOrders=loanOrderService.getLoanOrderByClientId(params);
		if(loanOrders.size()>0){
			 Shift.fatal(StatusCode.NVALID_ORDER_LOAN,"还有正在处理的借款订单！");	
		}
		List<RepayOrder> repayOrders=repayOrderService.getUnclearedOrderByClientId(params);
		if(repayOrders.size()>0){
			 Shift.fatal(StatusCode.INVALID_ORDER_REPAY,"还有未结清的借款订单！");	
		}
		int success=loanOrderService.insert(loanOrder);
		return new ObjectDataResponse<Integer>(success);
	}
	
	
	@RequestLogging
	@ApiOperation(value = "借款管理-是否能借款", notes = "借款管理-是否能借款")
	@RequestMapping(value = "/whetherCanLoan", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> whetherCanLoan(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody  LoanOrder loanOrder) throws NoSuchAlgorithmException, InvalidKeySpecException{
		Long clientId=loanOrder.getClientId();
		if(clientId == null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[clientId]会员主键为空啦！");	
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("clientId", clientId);
		List<LoanOrder>  loanOrders=loanOrderService.getLoanOrderByClientId(params);
		if(loanOrders.size()>0){
			 Shift.fatal(StatusCode.NVALID_ORDER_LOAN,"还有正在处理的借款订单！");	
		}
		//被拒后40天才能申请
		List<LoanOrder>  refuseLoanOrders=loanOrderService.getRefuseLoanOrderByClientId(params);
		if(refuseLoanOrders.size()>0){
			logger.info("************************************************************************");
			logger.info("************"+clientId+"************40天后才能申请");
			logger.info("************************************************************************");
			
			 Shift.fatal(StatusCode.NVALID_ORDER_LOAN,"还有正在处理的借款订单！");	
		}
		/**风控校验---黑名单拒绝申请*/
		ClientInfo  clientInfo=clientRiskService.getClientInfo(clientId);
		if(clientInfo.getType() == 0){
			 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
		}
		/**风控校验---18岁拒绝申请*/
		if(clientInfo.getAge() <=18){
			 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
		}
		/**风控校验---40岁拒绝申请*/
		if(clientInfo.getAge() >40){
			 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
		}
		/**风控校验---通讯录少于15拒绝申请*/
		int length=clientRiskService.getClientContactLength(clientId);
		if(length < 15){
			 Shift.fatal(StatusCode.INVALID_ORDER,"你尚未符合申请条件！");	
		}
		
		
		List<RepayOrder> repayOrders=repayOrderService.getUnclearedOrderByClientId(params);
		if(repayOrders.size()>0){
			 Shift.fatal(StatusCode.INVALID_ORDER_REPAY,"还有未结清的还款订单！");	
		}
		
		return new ObjectDataResponse<Integer>(1);
	}
	
	
	@RequestLogging
	@ApiOperation(value = "借款管理-借款订单列表-审核", notes = "借款管理-借款订单列表-审核")
	@RequestMapping(value = "/checkLoanOrder", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> checkLoanOrder(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		if(userId==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"未登录");
		}
		Long  id=loanOrder.getId();
		if(id==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[id]借款订单主键值为空啦");
		}
		Integer  status=loanOrder.getStatus();
		if(status==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[status]借款订单状态值为空啦");
		}else if(1 !=status && 2!=status){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS);
		}
		int success=loanOrderService.checkLoanOrder(loanOrder,userId);
		logService.addLog(userId, "借款管理-借款订单列表-审核", 0);
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "借款管理-放款订单列表", notes = "借款管理-放款订单列表")
	@RequestMapping(value = "/getLendingOrderList", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<LoanOrder>> getLendingOrderList(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		Page<LoanOrder> loanOrderList=loanOrderService.pageLendingOrder(loanOrder);
		logService.addLog(userId, "借款管理-放款订单列表", 0);
		return new ObjectDataResponse<Page<LoanOrder>>(loanOrderList);
	}
	@RequestLogging
	@ApiOperation(value = "借款管理-放款订单列表-放款", notes = "借款管理-放款订单列表-放款")
	@RequestMapping(value = "/doLending", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> doLending(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		if(userId==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"未登录");
		}
		Long  id=loanOrder.getId();
		if(id==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[id]借款订单主键值为空啦");
		}
		LoanOrder loanOrderData=loanOrderService.get(id);
		if(!"2".equals(loanOrderData.getStatus().toString())){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[id]此借款订单不能放款");
		}
		loanOrder.setClientId(null);
		logService.addLog(userId, "借款管理-放款订单列表-放款", 0);
		int success=loanOrderService.doLending(loanOrder,userId);
		if(0==success){
			Shift.fatal(StatusCode.SERVER_UNKNOWN_ERROR);
		}
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "我的借款记录", notes = "我的借款记录")
	@RequestMapping(value = "/getMyLoanOrderList", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<LoanOrder>> getMyLoanOrderList(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		Long  clientId=loanOrder.getClientId();
		if(clientId==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[clientId]会员主键值为空啦");
		}
		Page<LoanOrder> loanOrderList=loanOrderService.pageMyLoanOrder(loanOrder);
		return new ObjectDataResponse<Page<LoanOrder>>(loanOrderList);
	}
	
	@RequestLogging
	@ApiOperation(value = "借款管理-借款订单列表—查看详情", notes = "借款管理-借款订单列表—查看详情")
	@RequestMapping(value = "/getLoanOrderDetail", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<LoanOrder> getLoanOrderDetail(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		Long  id=loanOrder.getId();
		if(id==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[id]借款订单主键值为空啦");
		}
		LoanOrder loanOrderData=loanOrderService.getLoanOrderDetail(loanOrder.getId());
		logService.addLog(userId, "借款订单列表—查看详情", 0);
		return new ObjectDataResponse<LoanOrder>(loanOrderData);
	}
	
	
	@RequestLogging
	@ApiOperation(value = "借款管理-借款订单列表-备注", notes = "借款管理-借款订单列表-备注")
	@RequestMapping(value = "/loanRemark", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Integer> loanRemark(@ApiParam(hidden=true,name="登录用户ID")@CurrentUserId Long userId,@RequestBody LoanOrder loanOrder){
		if(userId==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"未登录");
		}
		Long id=loanOrder.getId();
		if(id==null){
			 Shift.fatal(StatusCode.INVALID_MODEL_FIELDS,"[id]借款订单主键为空啦");
		}
		int   success= loanOrderService.loanRemark(loanOrder,userId);
		
		return new ObjectDataResponse<Integer>(success);
	}
	
	@RequestLogging
	@ApiOperation(value = "借款管理-会员借款信息(0108)", notes = "借款管理-会员借款信息(0108)")
	@RequestMapping(value = "/getClientLoanOrder", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<ClientLoanOrder> getClientLoanOrder(@RequestBody ClientLoanOrder ClientLoanOrder){
		ClientLoanOrder   success= clientRiskService.getClientLoanOrder(ClientLoanOrder.getClientId());
		
		return new ObjectDataResponse<ClientLoanOrder>(success);
	}
	
}
